/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.afraid.poison.common;

import java.util.Arrays;

/**
 *
 * @author Andreas Schnaiter <rc.poison@gmail.com>
 */
public class NumberUtil {

	private static final char[] DIGITS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();

	private static long fromBase(int base, CharSequence digits) {
		if (null==digits||0==digits.length()) {
			return 0;
		}
		long number=0;
		int exp=0;
		for (char c : new StringBuilder(digits).reverse().toString().toCharArray()) {
			int index=Arrays.binarySearch(DIGITS, c);
			if (index<0) {
				throw new IllegalArgumentException("c: "+c);
			}
			number+=index*Math.pow(base, exp++);
		}
		return number;
	}

	public static long fromBase62(CharSequence digits) {
		return fromBase(62, digits);
	}

	public static long fromBase36(CharSequence digits) {
		return fromBase(36, digits);
	}

	public static long fromBase16(CharSequence digits) {
		return fromBase(16, digits);
	}

	private static String toBase(int base, long number) {
		StringBuilder digits=new StringBuilder().append(number==0 ? "0" : "");
		while (number!=0) {
			int mod=(int) (number%base);
			digits.append(DIGITS[mod]);
			number=number/base;
		}

		return digits.reverse().toString();
	}

	public static String toBase62(long number) {
		return toBase(62, number);
	}

	public static String toBase36(long number) {
		return toBase(36, number);
	}

	public static String toBase16(long number) {
		return toBase(16, number);
	}
}
